;(function($) {
  const sidebarWraps = {
    news: '#sidebar_news', //公告
    search: '#sidebar_search', //搜索
    links: '#sidebar_shortcut', // 常用链接
    recent: '#sidebar_recentposts', //最新随笔
    tags: '#sidebar_toptags', //我的标签
    score: '#sidebar_scorerank', //积分与排名
    category: '#sidebar_postcategory', //随笔分类
    record: '#sidebar_postarchive', //随笔档案
    recentComments: '#sidebar_recentcomments', //最近评论
    topview: '#sidebar_topviewedposts', //阅读排行
    topComents: '#sidebar_topcommentedposts', //评论排行
    topDig: '#topdigg_posts_wrap', //推荐排行
    catalog: '#catalog', //文章目录
  }
  const urls = {
    script: {
      flexible: 'flexible',
      lineNumbers: 'lineNumbers',
      icon: '//at.alicdn.com/t/font_1595820_cqb197x9339.js',
    },
    repositories: window.rep,
  }
  const icons = {
    dig: '#ac-dig', //推荐
    view: '#ac-view', //看
    search: '#ac-search', //搜索
    pens: '#ac-pens', //笔筒
    trending: '#ac-trending', //排行榜
    records: '#ac-records', //档案
    record: '#ac-record',
    categories: '#ac-categories', //分类
    category: '#ac-category',
    comments: '#ac-comments', //评论
    comment: '#ac-comment',
    tags: '#ac-tags', //标签
    tag: '#ac-tag',
    links: '#ac-links', //链接
    link: '#ac-link',
    pen: '#ac-pen', //笔
    catalog: '#ac-catalog', // 目录
    no1: 'ac-no1', //第一
    news: '#ac-notice', // 公告
    back2top: '#ac-back2top', //返回顶部
    github: '#ac-github', //github
    dark: '#ac-dark', //夜间模式
    light: '#ac-light', //白天
    look: '#ac-look',
    //count -> 20
    food: {
      pistachio: '#ac-food-pistachio',
      mochi: '#ac-food-mochi',
      cashew: '#ac-food-cashew',
      macaron: '#ac-food-macaron',
      cake: '#ac-food-cake',
      sushi: '#ac-food-sushi',
      eggyolkcake: '#ac-food-eggyolkcake',
      popsiple: '#ac-food-popsicle',
      taco: '#ac-food-taco',
      hotdog: '#ac-food-hotdog',
      pizza: '#ac-food-pizza',
      bread: '#ac-food-bread',
      popcorn: '#ac-food-popcorn',
      chips: '#ac-food-chips',
      doughnut: '#ac-food-doughnut',
      strawberry: '#ac-food-strawberry',
      pudding: '#ac-food-pudding',
      avocado: '#ac-food-avocado',
      pecan: '#ac-food-pecan',
      cookie: '#ac-food-cookie',
    },
  }

  class ACG {
    constructor() {
      this.defaultOptions = window.userOptions
      this.v = 'v1.5.0'
    }

    // 返回页面名称 'post' | 'index' | 'tag' | 'list' | 'tag' | 'taglist'
    get pageName() {
      if ($('#post_detail').length > 0) {
        return 'post'
      }
      if ($('.day').length > 0) {
        return 'index'
      }
      if ($('#taglist_main').length > 0) {
        return 'tag'
      }
      if ($('.entrylistPosttitle').length > 0) {
        return 'list'
      }
      if ($('#myposts').length > 0) {
        return 'tag'
      }
    }

    // 判断客户端 'phone' | 'pc'
    get userAgent() {
      const width = $(window).width()
      return width > 768 ? 'pc' : 'phone'
    }

    // 文章是否有可用来生成目录的标题
    get hasPostTitle() {
      return $('#cnblogs_post_body>h1,#cnblogs_post_body>h2,#cnblogs_post_body>h3,#cnblogs_post_body>h4').length === 0 ? false : true
    }

    // 初始化
    init() {
      this.loadCommonFiles()
      this.setBodyBackground()
      this.changeMode()
      this.setThemeColor()
      this.loadIconfont()
      this.setAvatar()
      this.setQrcode()
      this.scrollOnce()
      if (this.pageName === 'post') {
        this.setHighlight()
        this.setLinenumbers()
        this.setCopyBtn()
        this.setCatalog()
        this.setPostBtn()
        this.setActiveCatalogTitle()
        this.setCommentListAvatars()
        this.setPostSignature()
        this.setImagebox()
      }
      this.setMobileMenu()
      this.setBarrage()
      this.customBarrage()
      this.setBack2Top()
      this.setFooter()
      this.setHtmlTitleIcon()
      this.hideLoading()
    }

    // 只触发一次向上或向下,如果又重新反向滚动则再触发一次
    scrollOnce() {
      function scrollFunc() {
        let scrollDirection
        if (!scrollAction) {
          scrollAction = window.pageYOffset
        }
        let diff = scrollAction - window.pageYOffset
        if (diff < 0) {
          scrollDirection = 'down'
        } else if (diff > 0) {
          scrollDirection = 'up'
        } else {
          // First scroll event
        }
        scrollAction = window.pageYOffset
        return scrollDirection
      }
      let scrollAction, originalDir

      $(window).scroll(function() {
        let direction = scrollFunc()
        if (direction && originalDir != direction) {
          if (direction == 'down') {
            // console.log("down")
            $('#navigator').addClass('navigator-hide') // 头部导航隐藏
            $('#catalog').addClass('catalog-scroll-up') // 当头部导航隐藏目录随之向上移动
          } else {
            // console.log("up")
            $('#navigator').removeClass('navigator-hide')
            $('#catalog').removeClass('catalog-scroll-up')
          }
          originalDir = direction
        }
      })
    }

    // 当sideBarMain滚动出屏幕就固定目录
    setCatalogToggle() {
      const options = this.defaultOptions.catalog

      if (!options.enable) return
      if (!this.hasPostTitle) return
      if (this.pageName !== 'post') return
      if (this.userAgent !== 'pc') return

      var p = 0,
        t = 0,
        that = this
      $(window).scroll(
        that.throttle(
          function() {
            const bottom = that.getClientRect(document.querySelector('#sideBarMain')).bottom
            if (bottom <= 0) {
              $('#catalog').addClass('catalog-sticky')
              p = $(this).scrollTop()
              t <= p ? $('#catalog').addClass('catalog-scroll-up') : $('#catalog').removeClass('catalog-scroll-up')
              setTimeout(function() {
                t = p
              }, 0)
            } else {
              $('#catalog').removeClass('catalog-sticky')
            }
          },
          50,
          1000 / 60
        )
      )
    }

    // 设置目录活跃标题样式
    setActiveCatalogTitle() {
      const options = this.defaultOptions.catalog

      if (!options.enable) return
      if (!this.hasPostTitle) return
      if (this.pageName !== 'post') return
      if (this.userAgent !== 'pc') return

      var that = this
      $(window).scroll(
        that.throttle(
          function() {
            for (let i = $('#catalog ul li').length - 1; i >= 0; i--) {
              const titleId = $($('#catalog ul li')[i])
                .find('a')
                .attr('href')
                .replace(/[#]/g, '')
              const postTitle = document.querySelector(`#cnblogs_post_body [id='${titleId}']`)
              if (that.getClientRect(postTitle).top <= 10) {
                if ($($('#catalog ul li')[i]).hasClass('catalog-active')) return
                $($('#catalog ul li')[i]).addClass('catalog-active')
                $($('#catalog ul li')[i])
                  .siblings()
                  .removeClass('catalog-active')
                return
              }
            }
          },
          50,
          1000 / 60
        )
      )
    }

    // 返回顶部
    setBack2Top() {
      const option = this.defaultOptions.back2top
      const type = option.type
      if (this.userAgent !== 'pc') return
      if (!option.enable) return

      let $back2top
      if (type === 'simple') {
        $back2top = `<div id="back-to-top" style="display: block;">
                        <span class="percentage">0%</span>
                        <span id='back2top-icon'>${this.iconInSvg(icons.back2top)}</span>
                      </div>`
      }
      if (type === 'complex') {
        $back2top = `<div id="back-to-top" style="display: block;">
                    <div class="flow" style="height: 0%;"></div>
                    <span class="percentage">0%</span>
                    <span id='back2top-icon'>${this.iconInSvg(icons.back2top)}</span>
                  </div>`
      }

      $($back2top).appendTo('body')

      if (option.right !== '') {
        const toRight = option.right
        $('#back-to-top').css('right', toRight)
      }

      $('#back2top-icon').click(() => {
        $('html, body').animate(
          {
            scrollTop: 0,
          },
          300
        )
      })

      function compute() {
        const percentScrolled = (($(document).scrollTop() / ($(document).height() - $(window).outerHeight())) * 100).toFixed(2)
        const percentageHeight = percentScrolled + '%'
        const floor = Math.floor(percentScrolled)
        const integer = floor === 100 ? floor : `${floor}%`
        $('.percentage').text(integer)
        if (type !== 'complex') return
        $('.flow').css({
          height: percentageHeight,
        })
      }

      $(window).scroll(() => {
        requestAnimationFrame(compute)
      })
    }

    // 设置移动端菜单按钮
    setMobileMenu() {
      if (this.userAgent !== 'phone') return

      $('body').append(
        `<div id='side-btn-wrap'>
                    <div id='side-btn'>
                        <div id='side-btn-burger'></div>
                    </div>
                </div>`
      )

      const fixedBody = () => {
        let scrollTop = document.body.scrollTop || document.documentElement.scrollTop
        document.body.style.cssText += 'position:fixed;width:100%;top:-' + scrollTop + 'px;'
      }

      const looseBody = () => {
        let body = document.body
        body.style.position = ''
        let top = body.style.top
        document.body.scrollTop = document.documentElement.scrollTop = -parseInt(top)
        body.style.top = ''
      }

      $('#side-btn').click(function() {
        if ($(this).hasClass('side-btn-active')) {
          looseBody()
          $(this).removeClass('side-btn-active')
          $('#sideBar').css({
            visibility: 'hidden',
            'clip-path': 'circle(30px at calc(100%) 100%)',
            transition: 'all .5s ease-in-out',
          })
          setTimeout(() => {}, 500)
        } else {
          fixedBody()
          $(this).addClass('side-btn-active')
          $('#sideBar').css({
            visibility: 'visible',
            'clip-path': 'circle(100% at 50% 50%)',
            transition: 'all .3s ease-in-out',
          })
        }
      })
    }

    // 设置随笔页关注等按钮
    setPostBtn() {
      if (this.pageName !== 'post') return
      const $follow = $('#green_channel_follow').prop('outerHTML')
      const $like = $('#green_channel_digg').prop('outerHTML')
      const $wrap = `<div id='custom-post-btn'>${$follow}${$like}</div>`
      $('body').append($wrap)

      const likeText = $('#green_channel_digg').text()
      const followText = $('#green_channel_follow').text()

      likeText === '已推荐' ? $('#custom-post-btn #green_channel_digg').text('已赞') : $('#custom-post-btn #green_channel_digg').text('点赞')

      followText === '已关注' ? $('#custom-post-btn #green_channel_follow').text('已关') : $('#custom-post-btn #green_channel_follow').text('关注')
    }

    // 隐藏loading
    hideLoading() {
      $('#loading').fadeOut(800)
    }

    // 设置页面背景色
    setBodyBackground() {
      const options = this.defaultOptions.bodyBackground
      if (!options.enable) return

      $('#main,#navigator').css('opacity', `${options.opacity}`)

      if ($('#catalog').length > 0) {
        $('#main').css('opacity', `${options.opacity}`)
      }

      if (options.type === 'color') {
        $('body').css('background-color', `${options.value}`)
      } else if (options.type === 'img') {
        $('body').css('background-image', `url(${options.value})`)
        if (!options.repeat) {
          $('body').css({
            'background-repeat': `no-repeat`,
            'background-size': '100% 100%',
            'background-attachment': 'fixed',
          })
        }
      }
    }

    // 设置图片灯箱
    setImagebox() {
      const options = this.defaultOptions.imagebox
      if (this.pageName !== 'post') return
      if (!options.enable) return

      this.loadFiles(
        [
          {
            name: 'baguetteBox',
            type: 'js',
          },
          {
            name: 'baguetteBox',
            type: 'css',
          },
        ],
        () => {
          const imgList = $('#cnblogs_post_body img')
          if (imgList === 0) return
          $.each(imgList, i => {
            const item = $(imgList[i])
            const flag = item.attr('id')
            if (typeof flag === 'undefined' && item.outerWidth() > 50) {
              item.wrap("<a class='lightbox' href='" + item.attr('src') + "'></a>")
            }
          })
          baguetteBox.run('.lightbox')
        }
      )
    }

    // 设置头像
    setAvatar() {
      const avatar = this.defaultOptions.theme.avatar
      if (avatar === '' || $('#blog-news').length === 0) return

      const avatarStyle = {
        'margin-right': '0.2rem',
        width: '1.5rem',
        height: '1.5rem',
      }

      $('#blog-news').prepend(`<img id='custom-avatar' src='${avatar}' />`)
      $('#custom-avatar').css(avatarStyle)
    }

    // 设置二维码
    setQrcode() {
      const qrcode = this.defaultOptions.theme.qrcode
      if (qrcode === '' || $('#blog-news').length === 0) return

      const qrcodeStyle = {
        padding: '.187rem .267rem 0',
        width: '4rem',
      }

      $('#blog-news').before(`<img id='custom-qrcode' src='${qrcode}' />`)
      $('#custom-qrcode').css(qrcodeStyle)
    }

    // 设置主题色
    setThemeColor() {
      const option = this.defaultOptions.theme.color
      let themeColor = option === 'random' ? this.getRandomColor('rgba') : option
      $('head').append(`<style>:root{--themeColor: ${themeColor}}<style>`)
    }

    // --------- 弹幕 start -------

    //设置弹幕盒子
    setBarrage() {
      const options = this.defaultOptions.barrage
      if (!options.enable) return

      $('body').append(`<div id='barrage-wrap'></div>`)
    }

    /**
     * @description 发送弹幕
     * @param {Array} textList 弹幕列表
     */
    shootBarrage(textList) {
      const options = this.defaultOptions.barrage
      if (!options.enable) return
      const $wrap = document.querySelector('#barrage-wrap')
      const rect = this.getClientRect($wrap)
      const wrapWidth = rect.right - rect.left
      const wrapHeight = rect.bottom - rect.top

      textList.forEach(text => {
        const $barrage = document.createElement('span')
        const barrageStyle = `
									left: ${wrapWidth}px;
									top: ${this.getRandomNum(wrapHeight - 20, 1)}px;
									color: ${this.getRandomColor(options.colors)};
									opacity: ${options.opacity};
								`
        $barrage.style.cssText = barrageStyle
        $barrage.innerText = text
        $wrap.appendChild($barrage)
        const roll = timer => {
          const now = +new Date()
          const rect = this.getClientRect($barrage)
          let left = $barrage.offsetLeft
          roll.last = roll.last || now
          roll.timer = roll.timer || timer
          if (left < rect.left - rect.right) {
            $($barrage).remove()
          } else {
            if (now - roll.last >= roll.timer) {
              roll.last = now
              left -= 3
              $barrage.style.left = `${left}px`
            }
            window.requestAnimationFrame(roll)
          }
        }
        const randomSpeed = this.getRandomNum(100, 1)
        roll(randomSpeed)
      })
    }

    // 发送自定义随笔页首页弹幕
    customBarrage() {
      const barrage = this.defaultOptions.barrage
      if (!barrage.enable) return

      if (barrage.barrages.length !== 0) {
        setTimeout(() => {
          this.shootBarrage(barrage.barrages)
        }, 3000)
      }

      if (this.pageName === 'post' && barrage.postPageBarrages.length !== 0) {
        setTimeout(() => {
          this.shootBarrage(barrage.postPageBarrages)
        }, 3000)
      }

      if (this.pageName === 'index' && barrage.indexBarrages.length !== 0) {
        setTimeout(() => {
          this.shootBarrage(barrage.indexBarrages)
        }, 3000)
      }
    }

    // --------   弹幕 end -----
    //  ---- 切换夜间模式和日间模式 start -----

    // mode 初始化和点击切换
    changeMode() {
      const enableBarrage = this.defaultOptions.barrage.enable
      const isNight = new Date().getHours() > 19
      const $modeIcon = `<div id='mode-change'>${isNight ? this.iconInSvg(icons.dark) : this.iconInSvg(icons.light)}</div>`

      $('#navigator').prepend($modeIcon)

      if (isNight && localStorage.modeType !== 'dark') {
        this.shootBarrage(['夜深了，点击左上角小太阳试试暗色模式吧 🐱‍👤'])
      }

      localStorage.modeType === 'dark' ? this.changeModeToggle('dark') : this.changeModeToggle('light')

      $(document).on('click', '#mode-change', () => {
        $('body').addClass('mode-change')
        if ($('#mode-dark').length > 0) {
          this.changeModeToggle('light')
          if (!enableBarrage) return
          this.shootBarrage(['已成功切换为亮色模式 🌕'])
        } else {
          this.changeModeToggle('dark')
          if (!enableBarrage) return
          this.shootBarrage(['已成功切换为暗色模式 ✨'])
        }
      })
    }

    /**
     * @description 切换暗色主题和亮色主题
     * @param {String} mode 'dark' 或 'light'
     */
    changeModeToggle(mode = 'light') {
      const $dark = `<style id='mode-dark'>:root {--dark-background-g: #333;--dark-background-w: #555;--dark-background-e: #7c7c7c;--dark-text-0: #ccc;--dark-text-3: #ccc;--dark-text-4: #c0c0c0;--dark-text-5: #999;--dark-text-9: #7c7c7c;--dark-text-a: #000;}</style>`
      const $darkIcon = `<div id='mode-change'>${this.iconInSvg(icons.dark)}</div>`
      const $lightIcon = `<div id='mode-change'>${this.iconInSvg(icons.light)}</div>`

      if (mode === 'dark') {
        $('head').append($dark)
        $($darkIcon).replaceAll('#mode-change')
        localStorage.modeType = 'dark'
        $('#mode-change .icon').css('animation', 'none')
      } else {
        $('#mode-dark').remove()
        $($lightIcon).replaceAll('#mode-change')
        localStorage.modeType = 'light'
      }

      setTimeout(() => {
        $('body').removeClass('mode-change')
      }, 300)
    }

    //  ---- 切换夜间模式和日间模式 end -----

    // 显示评论列表头像
    setCommentListAvatars() {
      if (this.pageName !== 'post') return
      if ($('.feedbackItem').length === 0) return

      const show = () => {
        $('.feedbackItem').each(function() {
          let avatar = $(this)
            .children('.feedbackCon')
            .children('span:last')
            .html()

          avatar = avatar ? avatar.replace('http://', 'https://') : 'https://pic.cnblogs.com/face/sample_face.gif'

          $(`<img src=${avatar} class='avatar' />`).prependTo($(this).children('.feedbackCon'))
        })
      }

      if ($('.feedbackItem').length) {
        show()
      } else {
        let count = 1

        let intervalId = setInterval(() => {
          if ($('.feedbackItem').length) {
            clearInterval(intervalId)
            show()
          }
          if (count == 10) {
            clearInterval(intervalId)
          }
          count++
        }, 500)
      }
    }

    // 设置网站图标标题
    setHtmlTitleIcon() {
      const favicon = this.defaultOptions.theme.favicon
      const title = this.defaultOptions.theme.title

      if (favicon !== '') {
        $('head').append(`<link rel="icon" href=${favicon} sizes="32x32">`)
      }
      if (title !== '') {
        document.title = title
      }
    }

    // 加载必须的文件并隐藏loading
    loadCommonFiles() {
      const files = [
        {
          name: urls.script.flexible,
          type: 'js',
        },
      ]
      this.loadFiles(files)
    }

    // 设置随笔签名
    setPostSignature() {
      if (this.pageName !== 'post') return
      const enable = this.defaultOptions.postSignature.enable
      if (!enable) return
      const content = this.defaultOptions.postSignature.content
      const href = location.href.indexOf('#') === -1 ? location.href : location.href.substring(0, location.href.lastIndexOf('#'))
      let elements = ''
      for (let i = 0; i < content.length; i++) {
        elements += '<p>' + content[i] + '</p>'
      }
      const $signature = `<div id='post-signature'>
					<p>文章链接：${href}</p>
					${elements}
				</div>`
      $('#post-details').before($signature)
    }

    // 代码块复制按钮
    setCopyBtn() {
      if (this.pageName !== 'post') return
      const pres = $('.cnblogs-markdown').find('pre')
      if (!pres.length) return
      $.each(pres, (index, pre) => {
        $(pre).prepend(`<div class="copy-btns">copy</div>`)
      })
      $('pre').on('click', '.copy-btns', function() {
        const sel = window.getSelection()
        sel.removeAllRanges()
        const range = document.createRange()
        range.selectNode($(this).siblings('code.hljs')[0])
        sel.addRange(range)
        const txt = sel.anchorNode.innerText
        const area = $('<textarea name="" id="board" cols="30" rows="10"></textarea>')
        area.val(txt)
        area[0].select()
        document.execCommand('copy')
        $(this).text('copied')
      })
    }

    // 设置代码行号
    setLinenumbers() {
      if (this.pageName !== 'post') return
      const options = this.defaultOptions.lineNumbers
      if (!options.enable) return
        this.loadFiles(
          [
            {
              name: urls.script.lineNumbers,
              type: 'js',
            },
          ],
          () => {
            hljs.initLineNumbersOnLoad()
          }
        )
    }

    // 设置代码高亮
    setHighlight() {
      if (this.pageName !== 'post') return
      if ($('pre').length === 0) return

      const type = this.defaultOptions.highLight.type
      const atomOneDark = `<style>:root {--hl-base: #282c34;--hl-mono-1: #abb2bf;--hl-mono-3: #5c6370;--hl-hue-1: #56b6c2;--hl-hue-2: #61aeee;--hl-hue-3: #c678dd;--hl-hue-4: #98c379;--hl-hue-5: #e06c75;--hl-hue-6: #d19a66;--hl-hue-6-2: #e6c07b;--hl-tag: #abb2bf;}</style>`
      const atomOneLight = `<style>--hl-base: #fafafa;--hl-mono-1: #383a42;--hl-mono-3: #a0a1a7;--hl-hue-1: #0184bb;--hl-hue-2: #4078f2;--hl-hue-3: #a626a4;--hl-hue-4: #50a14f;--hl-hue-5: #e45649;--hl-hue-6: #986801;--hl-hue-6-2: #c18401;--hl-tag: #383A42;</style>`
      const github = `<style>--hl-base: #fff;--hl-mono-1: #333333;--hl-mono-3: #d73a49;--hl-hue-1: #0086b3;--hl-hue-2: #0086b3;--hl-hue-3: #d73a49;--hl-hue-4: #55a532;--hl-hue-5: #63a35c;--hl-hue-6: #6f42c1;--hl-hue-6-2: #6f42c1;--hl-tag: #d73a49;</style>`

      const actions = {
        atomOneDark,
        atomOneLight,
        github,
      }

      $('head').append(actions[type])
    }

    // 设置footer
    setFooter() {
      const nickName = $('#profile_block a:first')
        .text()
        .trim()
      const config = this.defaultOptions.links
      const $copyright = `<div id='copyright'>
					<span>
						Copyright ©
						${new Date().getFullYear()}
						${nickName}
					</span>
					<span>
						Build by ${'DIV Monster'.link('https://www.cnblogs.com/guangzan/')}
						🧦
						Theme ${'awesCnb'.link(urls.repositories.gitee)} ${this.v}
					</span>
				</div>`
      let $links = $('<ul id="links"></ul>')
      for (let i = 0; i < config.length; i++) {
        $links.append(`<li><a href='${config[i].link}'>${config[i].name}</a></li>`)
      }
      const $footer = `<footer>${$links.prop('outerHTML')}${$copyright}</footer>`
      $('body').append($footer)
    }

    //  ----- 随笔目录 start -----

    // 设置随笔目录
    setCatalog() {
      const options = this.defaultOptions.catalog
      if (!options.enable) return
      if (!this.hasPostTitle) return
      if (this.pageName !== 'post') return
      if (this.userAgent !== 'pc') return

      const $post = $($('#cnblogs_post_body'))
      const $catalogContainer = $('<div>')
      const $ulContainer = $('<ul>')
      const titleReg = /^h[1-3]$/

      $catalogContainer.attr('id', 'catalog').append($(`<div class='catListTitle'><h3>目录</h3></div>`))

      $post.children().each(function() {
        if (titleReg.test(this.tagName.toLowerCase())) {
          $(this).append("<a href='#catalog' class='title_back'></a>")
          let aEle = $('<a></a>')
          let hEle = $('<li></li>')
          const text = this.childNodes.length === 3 ? this.childNodes[1].nodeValue : this.childNodes[0].nodeValue
          aEle.attr('href', '#' + this.id).text(text)
          hEle.attr('class', this.nodeName.toLowerCase() + '-list').append(aEle)
          $ulContainer.append(hEle)
        }
      })

      $($catalogContainer.append($ulContainer)).appendTo('#sideBar')
      this.setCatalogPosition()
    }

    // 目录固定方式
    setCatalogPosition() {
      const position = this.defaultOptions.catalog.position

      const actions = {
        sidebar: () => {
          this.setCatalogToggle()
        },
        left: () => {
          $('#catalog').addClass('catalog-sticky-left')
          // this.moveCatalog()
        },
        right: () => {
          $('#catalog').addClass('catalog-sticky-right')
          // this.moveCatalog()
        },
      }

      actions[position]()
    }

    // ------- 随笔目录 end ----
    // --------- icon start --------

    // 设置侧边栏 icon
    setSidebarIcon() {
      const insert = () => {
        // 小块标题
        if ($(sidebarWraps.news).length > 0) {
          $(`${sidebarWraps.news} h3`).prepend(this.iconInSvg(icons.news))
        }
        if ($(sidebarWraps.search).length > 0) {
          $(`${sidebarWraps.search} h3`).prepend(this.iconInSvg(icons.search))
        }
        if ($(sidebarWraps.links).length > 0) {
          $(`${sidebarWraps.links} h3`).prepend(this.iconInSvg(icons.links))
          $(`${sidebarWraps.links} ul li a`).prepend(this.iconInSvg(icons.link))
        }
        if ($(sidebarWraps.recent).length > 0) {
          $(`${sidebarWraps.recent} h3`).prepend(this.iconInSvg(icons.pens))
          $(`${sidebarWraps.recent} ul li a`).prepend(this.iconInSvg(icons.pen))
        }
        if ($(sidebarWraps.tags).length > 0) {
          $(`${sidebarWraps.tags} h3`).prepend(this.iconInSvg(icons.tags))
          $(`${sidebarWraps.tags} ul li a`).prepend(this.iconInSvg(icons.tag))
        }
        if ($(sidebarWraps.score).length > 0) {
          $(`${sidebarWraps.score} h3`).prepend(this.iconInSvg(icons.trending))
        }
        if ($(sidebarWraps.category).length > 0) {
          $(`${sidebarWraps.category} h3`).prepend(this.iconInSvg(icons.categories))
          $(`${sidebarWraps.category} ul li a`).prepend(this.iconInSvg(icons.category))
        }
        if ($(sidebarWraps.record).length > 0) {
          $(`${sidebarWraps.record} h3`).prepend(this.iconInSvg(icons.records))
          $(`${sidebarWraps.record} ul li a`).prepend(this.iconInSvg(icons.record))
        }
        if ($(sidebarWraps.recentComments).length > 0) {
          $(`${sidebarWraps.recentComments} h3`).prepend(this.iconInSvg(icons.comments))
          $(`${sidebarWraps.recentComments} ul li a`).prepend(this.iconInSvg(icons.comment))
        }
        if ($(sidebarWraps.topview).length > 0) {
          $(`${sidebarWraps.topview} h3`).prepend(this.iconInSvg(icons.trending))
          $(`${sidebarWraps.topview} ul li a`).prepend(this.iconInSvg(icons.view))
        }
        if ($(sidebarWraps.topComents).length > 0) {
          $(`${sidebarWraps.topComents} h3`).prepend(this.iconInSvg(icons.trending))
          $(`${sidebarWraps.topComents} ul li a`).prepend(this.iconInSvg(icons.comment))
        }
        if ($(sidebarWraps.topDig).length > 0) {
          $(`${sidebarWraps.topDig} h3`).prepend(this.iconInSvg(icons.trending))
          $(`${sidebarWraps.topDig} ul li a`).prepend(this.iconInSvg(icons.dig))
        }
        if ($(sidebarWraps.catalog).length > 0) {
          $(`${sidebarWraps.catalog} h3`).prepend(this.iconInSvg(icons.catalog))
        }
      }

      if ($('#sidebar_topdiggedposts').length) {
        insert()
      } else {
        let count = 1

        let intervalId = setInterval(() => {
          if ($('#sidebar_topdiggedposts').length) {
            clearInterval(intervalId)
            show()
          }
          if (count == 10) {
            clearInterval(intervalId)
          }
          count++
        }, 500)
      }
    }

    // 设置 github icon
    setGithub() {
      const options = this.defaultOptions.github
      if (!options.enable) return
      const $githubIcon = `<a href=${options.url}>${this.iconInSvg(icons.github)}</a>`
      $('#navigator').prepend($githubIcon)
      $('#navigator .icon').css({
        color: `${options.color}`,
      })
    }

    // 首页文章题目 icon
    setIndexPosttitleIcon() {
      if (this.pageName !== 'index') return
      var that = this
      $('.postTitle').each(function() {
        $(this).prepend(that.iconInSvg(icons.pen))
      })
    }

    // 设置首页列表查看更多按钮
    setIndexPostLookIcon() {
      if (this.pageName !== 'index') return
      if ($('.day').length < 1) return
      var that = this
      $('.c_b_p_desc_readmore').each(function() {
        $(this).append(that.iconInSvg(icons.look))
      })
    }

    // 随笔分类页、随笔档案页题目 icon
    setEntrylistPosttitleIcon() {
      if (this.pageName !== 'list') return
      var that = this
      $('.entrylistPosttitle').each(function() {
        $(this).prepend(that.iconInSvg(icons.pen))
      })
    }

    // 设置随笔页文章题目icon
    setHeadlineIcon() {
      if (this.pageName !== 'post') return
      $('#topics .postTitle').prepend(this.iconInSvg(icons.pen))
    }

    // 文章标题 icon
    setPostTitleIcon() {
      if (this.pageName !== 'post') return
      const $h1 = $('#cnblogs_post_body:first>h1')
      const $h2 = $('#cnblogs_post_body:first>h2')
      const $title = $h1.length === 0 ? $h2 : $h1
      var that = this
      $($title).each(function() {
        const randomIconName = that.getRandomProperty(icons.food)
        const icon = icons.food[randomIconName]
        $(this).prepend(that.iconInSvg(icon))
      })
    }

    // 合并
    setIcons() {
      this.setSidebarIcon()
      this.setGithub()
      this.setIndexPosttitleIcon()
      this.setIndexPostLookIcon()
      this.setEntrylistPosttitleIcon()
      this.setHeadlineIcon()
      this.setPostTitleIcon()
    }

    // 加载 iconfont js
    loadIconfont() {
      const iconfont = [
        {
          name: urls.script.icon,
          type: 'jsCDN',
        },
      ]
      this.loadFiles(iconfont, () => {
        this.setIcons()
      })
    }

    // -------- icon end ----
    //---------- tools start ----------

    /**
     * @description
     * @param {Array} files [{name: '', type: 'js | css | jsCDN | cssCDN'}]
     * @param {Function} callback 回调函数 只能走一个
     */
    loadFiles(files, callback = function() {}) {
      const repositoriesUrl = urls.repositories.package + '/assets'
      for (let i = 0; i < files.length; i++) {
        const name = files[i].name
        const type = files[i].type
        const cssUrl = repositoriesUrl + '/css/' + name + '.css'
        const jsUrl = repositoriesUrl + '/js/' + name + '.min.js'
        const actions = {
          css: () => {
            $('head').append(`<link rel="stylesheet" href="${cssUrl}">`)
          },
          js: () => {
            $.getScript(jsUrl, () => {
              callback()
            })
          },
          cssCDN: () => {
            $('head').append(`<link rel="stylesheet" href="${name}">`)
          },
          jsCDN: () => {
            $.getScript(name, () => {
              callback()
            })
          },
          default: () => {
            console.error('Type error!')
          },
        }
        actions[type]()
      }
    }

    /**
     * @description 防抖函数
     * @param {Function} func 传入的函数
     * @param {Number} wait 等待
     * @param {Boolean} immediate 立即
     * @returns Function 返回的函数
     */
    debounce(func, wait, immediate) {
      var timeout
      return function() {
        var context = this,
          args = arguments
        var later = function() {
          timeout = null
          if (!immediate) func.apply(context, args)
        }
        var callNow = immediate && !timeout
        clearTimeout(timeout)
        timeout = setTimeout(later, wait)
        if (callNow) func.apply(context, args)
      }
    }

    // 简单的节流函数
    throttle(func, wait, mustRun) {
      var timeout,
        startTime = new Date()

      return function() {
        var context = this,
          args = arguments,
          curTime = new Date()

        clearTimeout(timeout)
        // 如果达到了规定的触发时间间隔，触发 handler
        if (curTime - startTime >= mustRun) {
          func.apply(context, args)
          startTime = curTime
          // 没达到触发间隔，重新设定定时器
        } else {
          timeout = setTimeout(func, wait)
        }
      }
    }

    /**
     * @description 指定icon插入svg
     * @param {String} icon xlink:href 的值
     * @returns svg标签
     */
    iconInSvg(icon) {
      return `<svg class="icon" aria-hidden="true"><use xlink:href="${icon}"></use></svg>`
    }

    /**
     * @description 随机对象属性
     * @param {Object} obj javascript对象
     * @returns 对象的随机属性
     */
    getRandomProperty(obj) {
      let result
      let count = 0
      for (let prop in obj) if (Math.random() < 1 / ++count) result = prop
      return result
    }

    /**
     * @description 获取随机颜色
     * @param {String} type 可选 颜色值类型 rgba 16
     * @returns 颜色值
     */
    getRandomColor(type) {
      let res = ''
      if (type === 'rgba') {
        const r = Math.floor(Math.random() * 256)
        const g = Math.floor(Math.random() * 256)
        const b = Math.floor(Math.random() * 256)
        const a = 0.6
        res = `rgba(${r},${g},${b},${a})`
      } else if (type === '16') {
        res = '#' + Math.floor(Math.random() * 0xffffff).toString(16)
      } else {
        const colors = type || ['#FE0302', '#FF7204', '#FFAA02', '#FFD302', '#FFFF00', '#A0EE00', '#00CD00', '#019899', '#4266BE', '#89D5FF', '#CC0273', '#CC0273']
        const random = Math.floor(Math.random() * colors.length)
        res = colors[random]
      }
      return res
    }

    /**
     * @description 获取元素相对与浏览器视口的位置
     * @param {Object} client document对象
     * @returns top, bottom, left, right, height, width
     */
    getClientRect(client) {
      const { top, bottom, left, right, height, width } = client.getBoundingClientRect()
      return {
        top,
        bottom,
        left,
        right,
        height: height || bottom - top,
        width: width || right - left,
      }
    }

    /**
     * @description 生成随机数 []
     * @param {Number} max 最大值
     * @param {Number} min 最小值
     * @returns 介于最大值与最小值闭区间的随机数
     */
    getRandomNum(max, min) {
      parseInt(Math.random() * (max - min + 1) + min, 10)
      return Math.floor(Math.random() * (max - min + 1) + min)
    }
    // -------- tools end -------
  }
  new ACG().init()
})(jQuery)
